import { notify } from "@/utils/anted";
import { ref, unref, reactive, toRefs, onMounted, nextTick } from "vue";
import type { Ref } from "vue";

interface Params {
  disableMounted?: boolean | Ref; // disableMounted = false | ref(false);
  mustQuery?: {}; // 查询条件，使用reactive创建的响应式变量，方便后期更新
  api: Function; // 查询列表的api方法
  delApi?: Function; // 删除数据的api方法
}
/**
 * 针对分页列表组件实现逻辑
 */
const useTableAnt = <T = any, Q = any>(params?: Params) => {
  // 列表ref
  const tableListRef = ref();
  // 定义状态
  const state = reactive({
    loading: false,
    page: {
      current: 1, // 当前页码
      size: 10, // 每页显示多少条
    },
    query: {} as any,
    tableList: [] as T[],
    pagination: {} as any,
  });

  onMounted(() => {
    // 禁用首次加载，方便组件中其他位置触发加载列表
    if (unref(params?.disableMounted)) return;
    queryData();
  });

  /**
   * 查询列表数据
   */
  const queryData = (pagination?: any) => {
    if (pagination) {
      const { current, pageSize } = pagination;
      state.page.current = current;
      state.page.size = pageSize;
    }
    // resolve正常处理完成后调用它，reject异常时调用它
    return new Promise((resolve, reject) => {
      state.loading = true;
      // 合并必须传递的查询条件
      // const query: any = params?.mustQuery;
      // console.log("params", query);
      // console.log("params?.mustQuery", params?.mustQuery);
      // let queryParam = {
      //   ...toRaw(query.modelStateRef),
      //   current: currentQueryPage,
      //   size: pageSizeQueryPage,
      // };
      const query = params?.mustQuery
        ? Object.assign({}, state?.query, params.mustQuery)
        : state.query;
      let paramsArr = {
        ...query,
        current: state.page.current,
        size: state.page.size,
      };
      params
        ?.api(paramsArr)
        .then((resp: any) => {
          const { total, records } = resp.data;
          state.tableList = []; // 清空
          nextTick(() => {
            // 列表数据
            state.pagination.total = total;
            state.pagination.showTotal = (total: any) => `共${total}条`;
            state.tableList = records;
          });
          // 正常响应
          resolve(resp);
        })
        .catch((error: Error) => {
          // 异常情况
          reject(error);
        })
        .finally(() => {
          state.loading = false;
        });
    });
  };

  // 点击删除
  const handleDelete = async (id: string) => {
    try {
      state.loading = true;
      if (params?.delApi) {
        await params.delApi(id);
        notify("删除成功！", { type: "success" });
        queryData();
      }
    } catch (error) {
    } finally {
      state.loading = false;
    }
  };

  return {
    tableListRef,
    ...toRefs(state),
    queryData,
    handleDelete,
  };
};

export default useTableAnt;
export { useTableAnt };
